from __future__ import division
import pygame
from pygame.locals import *
import potatogun

SCREENSIZE = (1000,600)
FIELDHEIGHT = 50
WHITE, BLACK, RED, GREEN, DARKGRAY = (255,255,255), (0,0,0), (255,0,0), (0,192,0), (90,90,90)
DEBUG = 0
FUELGAUGEHEIGHT = 50
FUELGAUGEWIDTH = 5

class CannonSprite:
   def __init__(self, images):
      self.images = images

   def getFuelPosition(self):
      return -80

   def getAngle(self, player):
      return 90-player.weapon.getDeclination()

   def render(self, surface, player, field):
      x = player.position[0]/field.lenght * SCREENSIZE[0]
      for n, (image, (dx,dy)) in enumerate(self.images):
         if n == 1:
            image = pygame.transform.rotozoom(image, self.getAngle(player), 1.0)
         surface.blit(image, image.get_rect( centerx=x+dx, bottom=SCREENSIZE[1]-FIELDHEIGHT+dy) )

      r=pygame.Rect((0,0), (FUELGAUGEWIDTH,FUELGAUGEHEIGHT))
      r.bottom=SCREENSIZE[1]-FIELDHEIGHT+dy - 10
      r.centerx=x-self.getFuelPosition()
      surface.fill( DARKGRAY, r )

      r.height= player.weapon.fuel_ammount/100 * FUELGAUGEHEIGHT
      r.bottom=SCREENSIZE[1]-FIELDHEIGHT+dy - 10
      surface.fill( RED, r )

      if DEBUG: print "rendering the cannon! at", x

class FlippedCannonSprite(CannonSprite):
   def __init__(self, images):
      self.images = [ (pygame.transform.flip(image, 1, 0), (-dx,dy)) for image, (dx,dy) in images ]

   def getAngle(self, player):
      return player.weapon.getDeclination()

   def getFuelPosition(self):
      return 80

imageCache = {}
class GameScene:
   def render(self, surface, field):
      surface.fill(BLACK)
      surface.fill(GREEN, surface.get_rect(height=FIELDHEIGHT, bottom=surface.get_rect().bottom))

      pixelSize = SCREENSIZE[0]/field.lenght
      for ammo in field.inFlightAmmo:
         ammoImage = imageCache.get(ammo.name)
         if ammoImage is None:
            ammoImage = pygame.image.load("art/%s.png"%ammo.name)
            imageCache[ammo.name] = ammoImage
         surface.blit( ammoImage, ammoImage.get_rect(center=(ammo.xloc*pixelSize, (SCREENSIZE[1]-FIELDHEIGHT)-ammo.yloc*pixelSize ) ) )

      for n, player in enumerate(field.players):
         self.sprites[n].render(surface, player, field)
      #screen.blit(l, l.get_rect(center=r.center) )

   def init(self):
      pygame.init()
      self.screen = pygame.display.set_mode(SCREENSIZE)
      self.clock = pygame.time.Clock()
      self.field = potatogun.Field()
      self.sprites = []
      self.activeAction = None

      images = [ (pygame.image.load("art/cannon-%s.png"%name),delta) for name, delta in [("feet",(25,0)), ("body",(-7,-23)), ("wheel",(0,0))] ]
      for n, player in enumerate(self.field.players):
         spriteClass = [FlippedCannonSprite, CannonSprite][n%2]
         self.sprites.append(spriteClass(images))

   def loop(self):
      playing = True

      repeat = False
      while playing:
         deltat = self.clock.tick(30)/1000
         weapon = self.field.getPlayer().weapon

         for event in pygame.event.get():
            if event.type == pygame.QUIT:
               playing = False
            elif event.type == KEYDOWN and event.key == K_1:
               self.field.cur_player = 0
            elif event.type == KEYDOWN and event.key == K_2:
               self.field.cur_player = 1
            elif event.type == KEYDOWN and event.key == K_ESCAPE:
               playing = False
            #elif event.type == KEYDOWN and event.key == K_s:
            elif event.type == KEYUP:
               self.activeAction = None
            elif event.type == KEYDOWN:
               keys = {
                  K_LEFT: (weapon.decreaseDeclination, True),
                  K_RIGHT: (weapon.increaseDeclination, True),
                  K_UP: (weapon.increaseFuel, True),
                  K_DOWN: (weapon.decreaseFuel, True),
                  K_PAGEUP: (weapon.nextAmmo, False),
                  K_PAGEDOWN: (weapon.prevAmmo, False),
                  K_SPACE: (weapon.fire, False),
               }
               self.activeAction, repeat = keys.get(event.key, (None, False))
         if self.activeAction is not None:
            self.activeAction()
            if not repeat:
               self.activeAction = None


         self.field.step(deltat)
         self.render(self.screen, self.field)
         pygame.display.flip()

g=GameScene()
g.init()
g.loop()
